package com.wetao.module_homework;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.daquexian.flexiblerichtextview.FlexibleRichTextView;
import com.tstudy.blepenlib.BlePenStreamManager;
import com.tstudy.blepenlib.data.BleDevice;
import com.tstudy.blepenlib.data.CoordinateInfo;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.EventBus.EventBusMessage;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.base.BaseResponse;
import com.wetao.lib_common.bean.request.CommitAnswerReq;
import com.wetao.lib_common.bean.request.CommitAnswerReq_vo;
import com.wetao.lib_common.bean.request.SmallTestCommitReq;
import com.wetao.lib_common.bean.request.SmallTestCommitReq_questionList;
import com.wetao.lib_common.bean.response.CommitAssistantAnswerResp;
import com.wetao.lib_common.bean.response.GetAssistantQuestionList;
import com.wetao.lib_common.bean.response.GetAssistantQuestionList2;
import com.wetao.lib_common.bean.response.QueryExamQuestionsResponse;
import com.wetao.lib_common.bean.response.StudentExamQuestion;
import com.wetao.lib_common.greendao.DBUtils;
import com.wetao.lib_common.greendao.model.WireExam;
import com.wetao.lib_common.greendao.model.WireQuestion;
import com.wetao.lib_common.greendao.model.WireQuestionPicture;
import com.wetao.lib_common.service.PlayService;
import com.wetao.lib_common.tsdBlePen.TsdPenUtil;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.BitmapUtil;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.DialogUtil;
import com.wetao.lib_common.utils.DialogXUtil;
import com.wetao.lib_common.utils.FileUtils;
import com.wetao.lib_common.utils.FormulaUtil;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.MyDividerItemDecoration;
import com.wetao.lib_common.utils.OptionStr;
import com.wetao.lib_common.utils.QuestionTypeUtil;
import com.wetao.lib_common.utils.SPUtils;
import com.wetao.lib_common.utils.StringUtil;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.utils.WrapContentLinearLayoutManager;
import com.wetao.lib_common.utils.oss.OssParams;
import com.wetao.lib_common.utils.oss.UploadOss;
import com.wetao.lib_common.view.dialogtiplib.util.DimenUtils;
import com.wetao.lib_common.view.graffiti.GraffitiOnTouchGestureListener;
import com.wetao.lib_common.view.graffiti.GraffitiTouchDetector;
import com.wetao.lib_common.view.graffiti.GraffitiView;
import com.wetao.lib_common.view.graffiti.IGraffitiTouchDetector;
import com.wetao.module_homework.adapter.HomeworkWireNumAdapter;
import com.wetao.module_homework.contract.HomeworkWireActivityCon;
import com.wetao.module_homework.presenter.HomeworkWireActivityPre;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.scilab.forge.jlatexmath.core.AjLatexMath;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.github.kbiakov.codeview.classifier.CodeProcessor;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = ConstantArouter.PATH_HOMEWORK_WIREACTIVITY)
public class HomeworkWireActivity extends BaseActivity<HomeworkWireActivityCon.View, HomeworkWireActivityPre>
        implements HomeworkWireActivityCon.View, FlexibleRichTextView.OnFlexibleListener {

    private static final int DOODLE_SAVE_TYPE_SWITCH = 101;
    private static final int DOODLE_SAVE_TYPE_SUBMIT = 102;
    private static final int DOODLE_SAVE_TYPE_EXIT = 103;
    private static final int DOODLE_SAVE_NEXT_QUESTION = 104;
    private static final int DOODLE_SAVE_ITEM_QUESTION = 105;


    @Autowired(name = "examName")
    String mExamName;

    @Autowired(name = "examId")
    int mExamId;

    @Autowired(name = "publishId")
    int mPublishId;

    @Autowired(name = "studentExamId")
    int mStudentExamId;

    @Autowired(name = "fromPath")
    String mFromPath;

    @Autowired(name = "roomId")
    String mRoomId;

    @Autowired(name = "isLine")
    int mIsLine;

    @Autowired
    boolean mIsTupu = false;

    @BindView(R2.id.tv_title)
    TextView tv_title;
    @BindView(R2.id.ll_h)
    LinearLayout ll_h;
    @BindView(R2.id.btn_next_question)
    Button btn_next_question;
    @BindView(R2.id.iv_no_data)
    ImageView iv_no_data;
    @BindView(R2.id.tv_no_data)
    TextView tv_no_data;

    @BindView(R2.id.rv_num)
    RecyclerView rv_num;
    @BindView(R2.id.ibtn_h_prev)
    ImageButton ibtn_h_prev;
    @BindView(R2.id.ibtn_h_next)
    ImageButton ibtn_h_next;
    private boolean mIsLastQuestion; //是否是最后一题
    private int mMaxCountLine = 0; //一行最多放多少个
    private int mNumfirstVisible;
    private int mNumfirstComplete;
    private int mNumlastVisible;
    private int mNumlastComplete;

    private HomeworkWireNumAdapter mHomeworkWireNumAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private MyDividerItemDecoration mDividerItemDecoration;


    private int mMoudle;
    private Bitmap mSmall_bitmap = null;
    private String mStudentId;

    private WireExam mWireExam;
    private int mCurQuesitonPostion;
    private WireQuestion mCurQuestion;
    private List<WireQuestionPicture> mCurQuestionPicList;
    private WireQuestionPicture mCurQuestionPic;

    @BindView(R2.id.ll_screen)
    LinearLayout ll_screen;
    @BindView(R2.id.tv_screen_0)
    TextView tv_screen_0;
    @BindView(R2.id.tv_screen_1)
    TextView tv_screen_1;
    @BindView(R2.id.ll_listen)
    LinearLayout ll_listen;
    @BindView(R2.id.iv_audio_play_or_pause)
    ImageView iv_audio_play_or_pause;
    @BindView(R2.id.tv_num_start_end)
    TextView tv_num_start_end;
    @BindView(R2.id.tv_audio_time)
    TextView tv_audio_time;
    @BindView(R2.id.btn_subject_tip)
    Button btn_subject_tip;

    @BindView(R2.id.frtv_exam_content)
    FlexibleRichTextView frtv_exam_content;
    @BindView(R2.id.ll_options)
    LinearLayout ll_options;
    private List<ImageView> mIvOptionList = new ArrayList<>();
    private List<FlexibleRichTextView> mFrtvOptionList = new ArrayList<>();
    private ConcurrentLinkedQueue<CoordinateInfo> mOffLineDots = new ConcurrentLinkedQueue();

    @BindView(R2.id.ll_contentParent)
    LinearLayout ll_contentParent;
    @BindView(R2.id.fl_doodle_0)
    FrameLayout fl_doodle_0;
    @BindView(R2.id.fl_doodle_1)
    FrameLayout fl_doodle_1;
    @BindView(R2.id.fl_doodle_2)
    FrameLayout fl_doodle_2;
    private Bitmap mDoodle_bimap_0;
    private Bitmap mDoodle_bimap_1;
    private Bitmap mDoodle_bimap_2;
    private float mO_w = 2149f;
    private float mO_h = 3023f;
    private float mV_w = 0;
    private float mV_h = 0;
    private float mScale = 1.0f;
    private int mLoadImgIndex = 0;
    private GraffitiView mGraffitiView;
    private GraffitiOnTouchGestureListener mGraffitiTouchGestureListener;
    private CoordinateInfo mCurDot;//当前正在绘制的点；
    private boolean mHavePic_temp = false;
    private boolean mSwitchPic_temp = false;
    private int mDoodleSaveType = 0;
    private float mTemp_x = 0f; //暂存转换后的坐标
    private float mTemp_y = 0f;
    private Float mMin_h = 0f;
    private Float mMax_h = 0f;
    private float mTran_h = 20f; //保存图片时，要截图，上下都多上这么多个像素
    private int mOssCount = 0;
    private List<OssParams> mOssParamsList = new ArrayList<>();
    private boolean mIsSubmitSuccess = true;

    private PlayService mPlayService;
    private PlayService.PlayBinder mPlayBinder;
    private String mAudioPath;

    private boolean mIsInitLoadingImg = false; //切题初始化加载图片中。
    private boolean mIsSwitchAndSavingImg = false;  //同一题切图片，或者切题之前保存图片
    private boolean mIsSubmiting = false; //提交
    private int mFtv_count = 0;
    private boolean mIsPenDown = false; //处理点码移动和弹起时的前提条件试，要有按下

    private boolean mIsPenAutoConnect = false; //判断蓝牙笔是否要自动连接
    private boolean mIsPenAutoConnecting = false;//判断已经搜索到蓝牙笔，正在自动连接

    private boolean mSmallTest_TeacherSubmit = false;
    private int mItemPostion_temp = 0;
    private Long mPicId_temp = null; //小测使用设置图片id的


    @Override
    public int getLayoutId() {
        return R.layout.homework_wire_activity;
    }

    @Override
    public boolean getIsBindTsdService() {
        return true;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return mTsdListener;
    }

    @Override
    public HomeworkWireActivityPre createPresenter() {
        return new HomeworkWireActivityPre(this);
    }

    @Override
    public HomeworkWireActivityCon.View createView() {
        return this;
    }

    @Override
    public void onComplete(FlexibleRichTextView view) {
        mFtv_count--;
    }

    @Override
    public void getQuestionListResult(BaseResponse<QueryExamQuestionsResponse> response) {
        if (null == response) {
            LogUtils.e("null == response");
            showNoData(true);
            return;
        }

        QueryExamQuestionsResponse data = response.getData();
        if (null == data) {
            LogUtils.e("null == data");
            showNoData(true);
            return;
        }

        List<StudentExamQuestion>  questionList = data.getQuestionList();
        if (null == questionList || 0 == questionList.size()) {
            LogUtils.e("null == questionList || 0 == questionList.size()");
            showNoData(true);
            return;
        }

        long wireExamId = DBUtils.getInstance(this).insertWireExam(new WireExam(null, mPublishId, mStudentExamId, mExamName, mExamId, data.getState(), data.getExamType(), ComUtil.getStringDate(), null, questionList.size(), 0));
        if(wireExamId < 0) {
            LogUtils.e("wireExamId < 0");
            showNoData(true);
            return;
        }

        if(mIsTupu) {
            mStudentExamId = data.getStudentExamId();
        }

        for(StudentExamQuestion item : questionList) {
            String options = null;
            if(item.getOptions() != null && item.getOptions().size() > 0) {
                options = StringUtil.strlistToString(item.getOptions(), "###");
            }
            String answers = null;
            if(item.getAnswers() != null && item.getAnswers().size() > 0) {
                answers = StringUtil.strlistToString(item.getAnswers(), "###");
            }
            DBUtils.getInstance(this).insertWireQuestion(new WireQuestion(null, item.getQuestionId(), item.getState(), item.getQuestionNo(), item.getQuestionScore(), item.getQuestionContent(), item.getQuestion()
                , options, item.getExplain(), answers, item.getQuestionType(), item.getIsSingle(), item.getAnswerType(), item.getAnswerContent(), item.getIsRight(), item.getMyScore(), item.getScreenIsView(), item.getScreenBegin(), item.getScreenEnd()
                , item.getQuestionScreen(), item.getScreenType(), item.getScreenId(), item.getListeningUrl(), item.getDuration(), item.getChapterId(), item.getIsCollect(), item.getIsUndrestand(), item.getQuestionDetailId()
                , item.getAnswerId(), item.getDoodle(), item.getVoiceComment(), item.getQuestionSite(), null, false, wireExamId));
        }
        mWireExam = DBUtils.getInstance(this).getWireExamByExamPublishIdAndStudentExamId(mPublishId, mStudentExamId);
        if(mWireExam == null) {
            LogUtils.e("插入数据库后，获得的数据为空");
            showNoData(true);
            return;
        }
        if(mIsTupu) {
            EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_LINE_TUPU_INTO, null));
        }
        initQuestionNumShow();
    }

    @Override
    public void getQuestionListFailed() {
        if(mWireExam == null) {
            LogUtils.e("getQuestionListFailed");
            showNoData(true);
        }
    }

    @Override
    public void getCommitAnswerResult(BaseResponse<CommitAssistantAnswerResp> response) {
        if (90012 == response.getCode()) {//该试题您已经提交作答了，不能再次作答
            LogUtils.e("该试题您已经提交作答了，不能再次作答");
            ToastUtil.initToast(response.getMsg() + "");
            mIsSubmiting = false;
            mIsSubmitSuccess = false;
            DialogXUtil.waitDialogDismiss();
            finish();
            return;
        }

        if(mIsTupu) {
            mPublishId = response.getData().getExamPublishId();
            mStudentExamId = response.getData().getStudentExamId();
        }

        deleteDataAndFile();
    }

    @Override
    public void getCommitAnswerFailed(int code) {
        mIsSubmiting = false;
        mIsSubmitSuccess = false;
        DialogXUtil.waitDialogDismiss();
        isSubmitSuccess();

        if(code == Constants.HTTP_ERROR.HTTP_TOKEN_OUT) {
            delayToOutLogin();
        }
    }

    @Override
    public void queryClassroomTestQuestionListResult(BaseResponse<GetAssistantQuestionList> resp) {
        if(resp.getData() != null) {
            GetAssistantQuestionList resp_data = resp.getData();
            initSmallTestData(resp_data);
        } else {
            LogUtils.e("m1: 返回数据为空");
        }
    }

    @Override
    public void queryClassroomTestQuestionListFailed() {
        finish();
    }

    @Override
    public void setTsdServiceConnected() {
        super.setTsdServiceConnected();

        mMoudle = mTsdServiceBinder.on_getmModule();
        if (mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
        } else {
            //设置为科学训练在线模式, 必须得设置，否则会屏蔽掉点阵数据
            if (null != mTsdServiceBinder) {
                if(mIsTupu) {
                    mTsdServiceBinder.on_setmModule(TsdService.MODULE_HOMEWORK_LINE_TUPU);
                } else {
                    mTsdServiceBinder.on_setmModule(TsdService.MODULE_HOMEWORK_LINE);
                }
            }
        }
        if(mPlayBinder == null) {
            initPlayService();
        }
    }

    @Override
    public void setTsdServiceDisConnect() {
        if (mMoudle == TsdService.MODULE_SMALLTEST_LINE) {

        } else {
            //必须得恢复科学训练点阵模式
            if (null != mTsdServiceBinder) {
                mTsdServiceBinder.on_setmModule(TsdService.MODULE_DEFAULT);
            }
        }
    }

    @Override
    public void init() {
        //禁止息屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        EventBus.getDefault().register(this);
        ////CodeProcessor.init(this);
        ////AjLatexMath.init(this);

        mStudentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);

        LogUtils.e("++++++++++++================init==============");
        mSmall_bitmap = BitmapUtil.ReadBitmapById_4444(this, R.drawable.doodle_bk);

        tv_title.setText(StringUtil.replaceAmp(mExamName));
        frtv_exam_content.setOnFlexibleListenerr(this);

        initRecyclerView();

    }

    @Override
    protected void onStop() {
        super.onStop();
        mPlayBinder.callPauseMusic();
    }

    @Override
    protected void onDestroy() {
        //deleteFileBackSmallTestView();
        if(mIsTupu) {
            EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_LINE_TUPU_OUT, null));
        }
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        EventBus.getDefault().unregister(this);
        if(playConnection != null) {
            unbindService(playConnection);
            playConnection = null;
        }
        super.onDestroy();
        if(mPlayBinder != null) {
            mPlayBinder = null;
        }
        if(mPlayService != null) {
            mPlayService.setCallback(null);
            mPlayService = null;
        }
    }

    @Override
    public void onBackPressed() {
        ////super.onBackPressed();
        if(!isClickable()) {
            return;
        }
        if(mWireExam == null) {
            finish();
        } else {
            exitActivity();
        }
    }

    private TsdService.OnDataReceiveListener mTsdListener = new TsdService.OnDataReceiveListener() {
        @Override
        public void onFinish() {
            finish();
        }

        @Override
        public void onErrTsdPen(int code, String msg) {
            if(mIsPenAutoConnect) {
                mIsPenAutoConnect = false;
                mIsPenAutoConnecting = false;
                mIsPenDown = false;
                DialogXUtil.waitDialogDismiss();
                showNoPenConnectDialog(true);
            }
        }

        @Override
        public void onRefreshScan(boolean isScaning) {
            if(mIsPenAutoConnect && !mIsPenAutoConnecting && !isScaning) {
                mIsPenAutoConnect = false;
                mIsPenAutoConnecting = false;
                mIsPenDown = false;
                DialogXUtil.waitDialogDismiss();
                showNoPenConnectDialog(true);
            }
        }

        @Override
        public void onAddDevice(BleDevice bleDevice) {
            if(mIsPenAutoConnect) {
                String mac = SPUtils.getInstance().getString(Constants.USER_PEN_MAC);
                if(bleDevice.getMac().equals(mac)) {
                    mIsPenAutoConnecting = true;
                    //mTsdServiceBinder.on_stopScan();//取消搜索
                    mTsdServiceBinder.on_penConnect(bleDevice);
                }
            }

        }

        @Override
        public void onPenConnectStatus(int code, BleDevice bleDevice) {
            if(mIsPenAutoConnect) {
                if (code == TsdService.CONN_PEN_SUCCESS) {
                    BlePenStreamManager.getInstance().getPenInfo();
                    /*mIsPenAutoConnect = false;
                    mIsPenAutoConnecting = false;
                    DialogXUtil.waitDialogDismiss();
                    BlePenStreamManager.getInstance().setRealtimeMode();
                    DialogXUtil.customDialogShow("自动重连成功！", "", "好的", true, R.drawable.common_dialog_icon_dui, new DialogXUtil.OnDialogXListen() {
                        @Override
                        public void onListenDialogOk() {

                        }

                        @Override
                        public void onListenDialogCancel() {

                        }

                        @Override
                        public void onListenDialogClose() {

                        }
                    });*/
                } else if (code == TsdService.CONN_PEN_FAIL || code == TsdService.CONN_PEN_DIS) {
                    mIsPenAutoConnect = false;
                    mIsPenAutoConnecting = false;
                    mIsPenDown = false;
                    DialogXUtil.waitDialogDismiss();
                    showNoPenConnectDialog(true);
                }
            }
        }

        @Override
        public void onGetPenInfo(int batteryPercent, int memoryPercent, int memoryByteNum) {
            LogUtils.i("作答界面获得笔的信息：batteryPercent:" + batteryPercent + ", memoryPercent:" + memoryPercent + ", memoryByteNum:" + memoryByteNum);
            if(!mIsPenAutoConnect) {
                return;
            }
            mIsPenAutoConnect = false;
            mIsPenAutoConnecting = false;
            DialogXUtil.waitDialogDismiss();
            if(memoryByteNum > 0) {
                DialogXUtil.customDialogShow("笔有离线数据，\r\n请转到智能笔界面", "", "好的", true, R.drawable.common_dialog_icon_dui, new DialogXUtil.OnDialogXListen() {
                    @Override
                    public void onListenDialogOk() {
                    }

                    @Override
                    public void onListenDialogCancel() {
                        ARouter.getInstance().build(ConstantArouter.PATH_PEN_PENMAINACTIVITY).navigation();
                    }

                    @Override
                    public void onListenDialogClose() {

                    }
                });
            } else {
                BlePenStreamManager.getInstance().setRealtimeMode();
                DialogXUtil.customDialogShow("自动重连成功！", "", "好的", true, R.drawable.common_dialog_icon_dui, new DialogXUtil.OnDialogXListen() {
                    @Override
                    public void onListenDialogOk() {

                    }

                    @Override
                    public void onListenDialogCancel() {

                    }

                    @Override
                    public void onListenDialogClose() {

                    }
                });
            }
        }

        @Override
        public void onCoordDraw(CoordinateInfo coordinateInfo) {
            if(coordinateInfo.state == TsdService.PEN_DOWN_MESSAGE) {
                mIsPenDown = true;
            } else if(coordinateInfo.state == TsdService.PEN_UP_MESSAGE) {
                if(!mIsPenDown) {
                    LogUtils.e("不处理弹起点：coordinateInfo.state == TsdService.PEN_UP_MESSAGE && !mIsPenDown");
                    return;
                }
                mIsPenDown = false;
            }
            if(!isDotable()) {
                LogUtils.e("不处理这个点，原因：isClickable() == false");
                return;
            }
            if(coordinateInfo.state == TsdService.PEN_COODINAT_MESSAGE && !mIsPenDown) {
                LogUtils.e("不处理移动点：coordinateInfo.state == TsdService.PEN_COODINAT_MESSAGE && !mIsPenDown");
                return;
            }

            if(mWireExam == null || mCurQuestion == null) {
                LogUtils.e("不处理这个点，原因：mWireExam == null || mCurQuestion == null");
                return;
            }

            if(!QuestionTypeUtil.isSubjectQuestion(mCurQuestion.getQuestionType())) {
                LogUtils.e("不处理这个点, 原因：不是主观题");
                return;
            }
            mOffLineDots.offer(coordinateInfo);
            nextDots();
        }

        @Override
        public void onTeacherExitSmallTest() {
            if(!mIsSubmiting) {
                mSmallTest_TeacherSubmit = true;
                clickSubmit_pre();
            } else {
                DialogXUtil.customDialogDismiss();
                finish();
            }
        }
    };

    @OnClick({R2.id.iv_back,
            R2.id.btn_next_question,
            R2.id.ibtn_h_prev,
            R2.id.ibtn_h_next,
            R2.id.tv_screen_0,
            R2.id.tv_screen_1,
            R2.id.iv_audio_play_or_pause
    })
    public void onClickView(View v) {
        int id = v.getId();
        if(!isClickable()) {
            return;
        }
        if(id == R.id.iv_back) {
            if(mWireExam == null) {
                finish();
            } else {
                exitActivity();
            }
        } else if(id == R.id.ibtn_h_prev) {
            prevLine();
        } else if(id == R.id.ibtn_h_next) {
            nextLine();
        } else if(id == R.id.iv_audio_play_or_pause) {
            if(mPlayBinder != null) {
                if(mPlayBinder.callIsPlaying()) {
                    mPlayBinder.callPauseMusic();
                } else {
                    mPlayBinder.callPlayMusic();
                }
            }
        } else if(id == R.id.tv_screen_0) {
            setScreenTab(true);
        } else if(id == R.id.tv_screen_1) {
            setScreenTab(false);
        } else if(id == R.id.btn_next_question) {
            if(mIsLastQuestion) {
                //提交作答
                int num = getNoAnswerNum();
                if(num > 0) {
                    DialogXUtil.customDialogShow("你有" + num + "道题未进行作答，\r\n确定提交作答吗？" , "提交", "取消", new DialogXUtil.OnDialogXListen() {
                        @Override
                        public void onListenDialogOk() {
                            clickSubmit_pre();
                        }

                        @Override
                        public void onListenDialogCancel() {

                        }

                        @Override
                        public void onListenDialogClose() {

                        }
                    });
                } else {
                    DialogXUtil.customDialogShow("确定要提交吗？" , "提交", "取消", new DialogXUtil.OnDialogXListen() {
                        @Override
                        public void onListenDialogOk() {
                            clickSubmit_pre();
                        }

                        @Override
                        public void onListenDialogCancel() {

                        }

                        @Override
                        public void onListenDialogClose() {

                        }
                    });
                }
            } else {
                //下一题
                if(mGraffitiView != null) {
                    saveGraffitiView(DOODLE_SAVE_NEXT_QUESTION);
                } else {
                    clickNextQuestion();
                }
            }
        }
    }

    private void clickNextQuestion() {
        WireQuestion question = mHomeworkWireNumAdapter.getNextQuestion();
        int temp = mHomeworkWireNumAdapter.getNextPosition();
        if(temp >= 0) {
            if(temp < mNumfirstComplete) {
                prevLine();
            } else if(temp > mNumlastComplete) {
                nextLine();
            }
        }
        mHomeworkWireNumAdapter.setmQuestionId(question.getQuestionId());
    }

    private void clickItemQuestion() {
        WireQuestion question = mHomeworkWireNumAdapter.getQuestion(mItemPostion_temp);
        mHomeworkWireNumAdapter.setmQuestionId(question.getQuestionId());
    }

    /**
     * 初始化音频播放服务
     */
    private void initPlayService() {
        Intent playService = new Intent(this, PlayService.class);
        this.bindService(playService, playConnection, Service.BIND_AUTO_CREATE);
    }
    /**
     * 播放音频
     * @param url
     */
    private void setPlayMusicUrl(String url) {
        mAudioPath = url;
        mPlayBinder.callSetmUrl(url);

    }

    private ServiceConnection playConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mPlayBinder = (PlayService.PlayBinder) service;
            mPlayService = mPlayBinder.getService();
            mPlayService.setCallback(new PlayService.CallbackPlay() {
                @Override
                public void onDataTestChange(String data) {

                }

                @Override
                public void onMusicStausChange(int status) {
                    if(status == PlayService.STATUS_MUSIC_PLAY) {
                        iv_audio_play_or_pause.setImageResource(R.drawable.homework_icon_pause);
                    } else {
                        iv_audio_play_or_pause.setImageResource(R.drawable.homework_icon_play);
                    }
                }

                @Override
                public void onCurrentPosition(int currentPosition, int duration) {
                    runOnUiThread(() -> {
                        if (duration > 0 && currentPosition <= duration) {
                            tv_audio_time.setText(String.format("%s/%s", ComUtil.strToTime(currentPosition / 1000 + ""), ComUtil.strToTime(duration / 1000 + "")));
                        }
                    });
                }

                @Override
                public void onCompletion() {

                }

                @Override
                public void OnDuration(int duration) {

                }

                @Override
                public void onLoadedUrl() {
                }
            });

            mV_w = ll_contentParent.getWidth();
            mScale = mV_w / mO_w;
            LogUtils.e("获得控件的宽：mV_w = " + mV_w + ", mO_w = " + mO_w + ", mScale = " + mScale);
            fl_doodle_0.setLayoutParams(new LinearLayout.LayoutParams((int)mV_w, (int)(mO_h * mScale)));
            fl_doodle_1.setLayoutParams(new LinearLayout.LayoutParams((int)mV_w, (int)(mO_h * mScale)));
            fl_doodle_2.setLayoutParams(new LinearLayout.LayoutParams((int)mV_w, (int)(mO_h * mScale)));

            if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
                if(mWireExam == null) {
                    getPresenter().queryClassroomTestQuestionList(ComUtil.getHashmapByStr(
                            new String[]{"examPublishId", "studentExamId"},
                            new String[]{mPublishId + "", ""}), false, false);
                }
            } else {
                if(mWireExam == null) {
                    mWireExam = DBUtils.getInstance(HomeworkWireActivity.this).getWireExamByExamPublishIdAndStudentExamId(mPublishId, mStudentExamId);
                    if(mWireExam == null) {
                        LogUtils.i("---从后台获取数据");
                        if(mIsTupu) {
                            getPresenter().courseExamQuestionList((HashMap<String, Object>) ComUtil.getHashmapByStr(
                                    new String[]{"examId"}, new Object[]{mExamId}), true, false);
                        } else {
                            getPresenter().getQuestionList((HashMap<String, Object>) ComUtil.getHashmapByStr(
                                    new String[]{"examPublishId", "studentExamId"}, new Object[]{mPublishId, mStudentExamId}), false, false);
                        }
                    } else {
                        LogUtils.i("---从数据库获取数据");
                        initQuestionNumShow();
                    }
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    private void showNoData(boolean isNo) {
        if(isNo) {
            if(ll_h.getVisibility() == View.VISIBLE) {
                iv_no_data.setVisibility(View.VISIBLE);
                tv_no_data.setVisibility(View.VISIBLE);

                ll_h.setVisibility(View.GONE);
                btn_next_question.setVisibility(View.GONE);
            }
        } else {
            if(ll_h.getVisibility() == View.GONE) {
                iv_no_data.setVisibility(View.GONE);
                tv_no_data.setVisibility(View.GONE);

                ll_h.setVisibility(View.VISIBLE);
                btn_next_question.setVisibility(View.VISIBLE);
            }
        }
    }

    private void initRecyclerView() {
        mLayoutManager = new WrapContentLinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mHomeworkWireNumAdapter = new HomeworkWireNumAdapter();
        rv_num.setLayoutManager(mLayoutManager);
        mDividerItemDecoration = new MyDividerItemDecoration(this, LinearLayoutManager.HORIZONTAL, R.drawable.divider_mileage_voice_class);
        //rv_num.addItemDecoration(mDividerItemDecoration);
        rv_num.setItemAnimator( new DefaultItemAnimator());
        rv_num.setAdapter(mHomeworkWireNumAdapter);
        ((HomeworkWireNumAdapter)mHomeworkWireNumAdapter).setOnItemClickListener(new HomeworkWireNumAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                LogUtils.i("onItemClick--" + position);
                if(!isClickable()) {
                    return;
                }
                mItemPostion_temp = position;
                if(mGraffitiView != null) {
                    saveGraffitiView(DOODLE_SAVE_ITEM_QUESTION);
                } else {
                    clickItemQuestion();
                }
            }

            @Override
            public void onPositionChange(int position) {
                mCurQuesitonPostion = position;

                if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
                    mCurQuestion = mWireExam.getQuestionList2().get(position);
                    mCurQuestionPicList = mCurQuestion.getWireQuestionPictureList2();
                } else {
                    mCurQuestion = mWireExam.getQuestionList().get(position);
                    mCurQuestionPicList = mCurQuestion.getWireQuestionPictureList();
                }
                setQuestionView();
            }

            @Override
            public void onIsLastQuestion(boolean isLastQuestion) {
                mIsLastQuestion = isLastQuestion;
                if(mIsLastQuestion) {
                    btn_next_question.setText("提交作答");
                } else {
                    btn_next_question.setText("下一题");
                }
            }
        });
        rv_num.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                LogUtils.i("m1: onScrolled dx = " + dx + ", dy = " + dy);

                LinearLayoutManager layoutManager= (LinearLayoutManager) recyclerView.getLayoutManager();
                if(layoutManager != null) {
                    mNumfirstVisible  = layoutManager.findFirstVisibleItemPosition();
                    mNumfirstComplete = layoutManager.findFirstCompletelyVisibleItemPosition();
                    mNumlastVisible  = layoutManager.findLastVisibleItemPosition();
                    mNumlastComplete = layoutManager.findLastCompletelyVisibleItemPosition();
                    LogUtils.i("m1: onScrolled -- FirstVisible = " + mNumfirstVisible + ", FirstComplete = " + mNumfirstComplete +", LastVisible = " +  mNumlastVisible +", LastComplete = " +  mNumlastComplete);
                    //HomeworkNumAdapter.NumHolder numHolder = (HomeworkNumAdapter.NumHolder)rv_num.findViewHolderForAdapterPosition(firstVisible);
                    if(mNumlastComplete - mNumfirstComplete > mMaxCountLine) {
                        mMaxCountLine = mNumlastComplete - mNumfirstComplete;
                    }
                    if(mNumfirstComplete == 0) {
                        ibtn_h_prev.setImageResource(R.drawable.common_rc_left_s);
                        ibtn_h_prev.setClickable(false);
                    } else {
                        ibtn_h_prev.setImageResource(R.drawable.common_rc_left_n);
                        ibtn_h_prev.setClickable(true);
                    }

                    if(mNumlastComplete == mHomeworkWireNumAdapter.getItemCount() - 1) {
                        ibtn_h_next.setImageResource(R.drawable.common_rc_right_s);
                        ibtn_h_next.setClickable(false);
                    } else {
                        ibtn_h_next.setImageResource(R.drawable.common_rc_right_n);
                        ibtn_h_next.setClickable(true);
                    }
                }
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void prevLine() {
        if(mNumfirstComplete - mMaxCountLine >= 0) {
            rv_num.scrollToPosition(mNumfirstComplete - mMaxCountLine);
        } else {
            rv_num.scrollToPosition(0);
        }
    }

    private void nextLine() {
        if(mNumlastComplete + mMaxCountLine >= mHomeworkWireNumAdapter.getItemCount()) {
            rv_num.scrollToPosition(mHomeworkWireNumAdapter.getItemCount() - 1);
        } else {
            rv_num.scrollToPosition(mNumlastComplete + mMaxCountLine);
        }
    }

    private boolean isClickable() {
        if(isDotable() && !mIsPenDown && !mIsSwitchAndSavingImg && mOffLineDots.isEmpty()) {
            return true;
        }
        LogUtils.e("isClickable()不通过：" + ", mIsPenDown:" + mIsPenDown  + ", mIsSwitchAndSavingImg:" + mIsSwitchAndSavingImg
                + ", mOffLineDots.isEmpty():" + mOffLineDots.isEmpty());
        return false;
    }

    private boolean isDotable() {
        if(mFtv_count == 0 && !mIsInitLoadingImg &&  !mIsSubmiting) {
            return true;
        }
        LogUtils.e("isDotable()不通过：mFtv_count:" + mFtv_count + ", mIsInitLoadingImg:" + mIsInitLoadingImg
                + ", mIsSubmiting:" + mIsSubmiting);
        return false;
    }

    private boolean isNextDot() {
        if(mFtv_count == 0 && !mIsInitLoadingImg && !mIsSwitchAndSavingImg && !mIsSubmiting && !mOffLineDots.isEmpty()) {
            LogUtils.e("isNextDot()通过");
            return true;
        }

        LogUtils.e("isNextDot()不通过：mFtv_count:" + mFtv_count + ", mIsInitLoadingImg:" + mIsInitLoadingImg + ", mIsSwitchAndSavingImg:" + mIsSwitchAndSavingImg
                + ", mIsSubmiting:" + mIsSubmiting+ ", mOffLineDots.isEmpty():" + mOffLineDots.isEmpty());
        return false;
    }

    private void initQuestionNumShow() {
        showNoData(false);
        List<WireQuestion> questionList = null;
        if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
            questionList = mWireExam.getQuestionList2();
        } else {
            questionList = mWireExam.getQuestionList();
        }
        mHomeworkWireNumAdapter.updateData(questionList);
        for(int i = 0; i < questionList.size(); i++) {
            WireQuestion item = questionList.get(i);
            if(QuestionTypeUtil.isObjectQuestion(item.getQuestionType())) {
                if(StringUtil.isEmpty(item.getMyAnswer())) {
                    mHomeworkWireNumAdapter.setmCurPosition(i);
                    return;
                }
            } else if(QuestionTypeUtil.isSubjectQuestion(item.getQuestionType())) {
                if(!item.getIsSubjectMyAns()) {
                    mHomeworkWireNumAdapter.setmCurPosition(i);
                    return;
                }
            }
        }
        mHomeworkWireNumAdapter.setmCurPosition(0);
    }

    private void setQuestionView() {
        if(mCurQuestion.getScreenId() != null) {
            ll_screen.setVisibility(View.VISIBLE);
            int position = mHomeworkWireNumAdapter.getmCurPosition() - 1;
            List<WireQuestion> questionList = null;
            if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
                questionList = mWireExam.getQuestionList2();
            } else {
                questionList = mWireExam.getQuestionList();
            }
            if(position >= 0 && position <questionList.size()
                    && questionList.get(position).getScreenId().intValue() == mCurQuestion.getScreenId().intValue()) {
                setScreenTab(false);
            } else {
                setScreenTab(true);
            }
        } else {
            ll_screen.setVisibility(View.GONE);
            setScreenTab(false);
        }

        if(QuestionTypeUtil.isObjectQuestion(mCurQuestion.getQuestionType())) {
            setOptionsView();
        }

        if(StringUtil.isEmpty(mCurQuestion.getListeningUrl())) {
            ll_listen.setVisibility(View.GONE);
            if(mPlayBinder.callIsPlaying()) {
                mPlayBinder.callPauseMusic();
            }

        } else {
            ll_listen.setVisibility(View.VISIBLE);
            if(!mCurQuestion.getListeningUrl().equals(mAudioPath)) {
                Integer start = null;
                Integer end = null;
                List<WireQuestion> questionList = null;
                if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
                    questionList = mWireExam.getQuestionList2();
                } else {
                    questionList = mWireExam.getQuestionList();
                }
                for(WireQuestion item : questionList) {
                    if(mCurQuestion.getListeningUrl().equals(item.getListeningUrl())) {
                        if(start == null) {
                            start = item.getQuestionNo();
                        }
                        end = item.getQuestionNo();
                    } else if(end != null) {
                        break;
                    }
                }

                tv_num_start_end.setText("听力（" + start + " - " + end + "）");
                tv_audio_time.setText(String.format("%s/%s", "00:00", ComUtil.stringForTime(mCurQuestion.getDuration() == null ? 0 : mCurQuestion.getDuration().intValue() * 1000)));
                setPlayMusicUrl(mCurQuestion.getListeningUrl());
            }
        }

        if(QuestionTypeUtil.isSubjectQuestion(mCurQuestion.getQuestionType())) {
            btn_subject_tip.setVisibility(View.VISIBLE);

            if(mTsdServiceBinder.on_getmBleDevice() == null) {
                showNoPenConnectDialog(false);
            }
        } else {
            btn_subject_tip.setVisibility(View.GONE);
        }

        initLoadQuestionPicture();
    }

    private void setScreenTab(boolean isScreenTab) {
        frtv_exam_content.resetTextView();
        final StringBuilder stringBuilder = new StringBuilder();

        if(isScreenTab) {
            tv_screen_0.setBackgroundResource(R.drawable.shape_line_on_right_d);
            tv_screen_0.setTextColor(Color.parseColor("#ffffff"));
            tv_screen_1.setBackgroundResource(R.drawable.shape_line_on_left);
            tv_screen_1.setTextColor(Color.parseColor("#333333"));

            ll_options.setVisibility(View.GONE);
            stringBuilder.append(FormulaUtil.reLatex(mCurQuestion.getQuestionScreen()));
        } else {
            tv_screen_0.setBackgroundResource(R.drawable.shape_line_on_right);
            tv_screen_0.setTextColor(Color.parseColor("#333333"));
            tv_screen_1.setBackgroundResource(R.drawable.shape_line_on_left_d);
            tv_screen_1.setTextColor(Color.parseColor("#ffffff"));

            if(QuestionTypeUtil.isTrueOrFalseQuestion(mCurQuestion.getQuestionType())) {
                ll_options.setVisibility(View.VISIBLE);
            } else if(QuestionTypeUtil.isObjectQuestion(mCurQuestion.getQuestionType()) && mCurQuestion.getOptions() != null) {
                ll_options.setVisibility(View.VISIBLE);
            } else {
                ll_options.setVisibility(View.GONE);
            }
            if(mCurQuestion.getQuestionNo() != null) {
                stringBuilder.append(String.format("%s. ",mCurQuestion.getQuestionNo()));
            }
            stringBuilder.append(FormulaUtil.reLatex(mCurQuestion.getQuestion()));
        }
        mFtv_count++;
        frtv_exam_content.setText(stringBuilder.toString());
    }

    private void setOptionsView() {
        resetFrtView();
        mIvOptionList.clear();
        mFrtvOptionList.clear();

        ll_options.removeAllViews();


        if(QuestionTypeUtil.isTrueOrFalseQuestion(mCurQuestion.getQuestionType())) {
            for(int i = 0; i < 2; i++) {
                View selectView = LayoutInflater.from(this).inflate(R.layout.homework_wire_item_option, ll_options, false);
                ll_options.addView(selectView);
                ImageView iv_option = selectView.findViewById(R.id.iv_options);
                mIvOptionList.add(iv_option);
                FlexibleRichTextView frtv_option = selectView.findViewById(R.id.frtv_options);
                frtv_option.setOnFlexibleListenerr(HomeworkWireActivity.this);
                mFrtvOptionList.add(frtv_option);
                List<String> myAns = StringUtil.strToList(mCurQuestion.getMyAnswer(), ",");

                if(i == 0) {
                    if(myAns != null && myAns.contains("T")) {
                        iv_option.setImageResource(R.drawable.homework_round_radio_select);
                    }
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(QuestionTypeUtil.TRUE_FALSE_V);
                    mFtv_count++;
                    frtv_option.setText(stringBuilder.toString());

                    selectView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(StringUtil.isEmpty(mCurQuestion.getMyAnswer())) {
                                if(mWireExam.getDealNum() == null) {
                                    setDealNum(1);
                                } else {
                                    setDealNum(mWireExam.getDealNum().intValue() + 1);
                                }
                                if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                                    DBUtils.getInstance(HomeworkWireActivity.this).updateWireExam(mWireExam);
                                }
                            }
                            mCurQuestion.setMyAnswer("T");
                            if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                                DBUtils.getInstance(HomeworkWireActivity.this).updateWireQuestion(mCurQuestion);
                            }
                            for(ImageView item : mIvOptionList) {
                                if(item == iv_option) {
                                    item.setImageResource(R.drawable.homework_round_radio_select);
                                } else {
                                    item.setImageResource(R.drawable.homework_round_radio_unselect);
                                }
                            }
                        }
                    });
                } else {
                    if(myAns != null && myAns.contains("F")) {
                        iv_option.setImageResource(R.drawable.homework_round_radio_select);
                    }
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(QuestionTypeUtil.TRUE_FALSE_X);
                    mFtv_count++;
                    frtv_option.setText(stringBuilder.toString());

                    selectView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(StringUtil.isEmpty(mCurQuestion.getMyAnswer())) {
                                if(mWireExam.getDealNum() == null) {
                                    setDealNum(1);
                                } else {
                                    setDealNum(mWireExam.getDealNum().intValue() + 1);
                                }
                                if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                                    DBUtils.getInstance(HomeworkWireActivity.this).updateWireExam(mWireExam);
                                }
                            }
                            mCurQuestion.setMyAnswer("F");
                            if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                                DBUtils.getInstance(HomeworkWireActivity.this).updateWireQuestion(mCurQuestion);
                            }
                            for(ImageView item : mIvOptionList) {
                                if(item == iv_option) {
                                    item.setImageResource(R.drawable.homework_round_radio_select);
                                } else {
                                    item.setImageResource(R.drawable.homework_round_radio_unselect);
                                }
                            }

                            //切换下一题
                            autoNextQuestion();
                        }
                    });
                }
            }
        } else if(mCurQuestion.getOptions() != null){
            List<String> ans = StringUtil.strToList(mCurQuestion.getOptions(), "###");
            if(ans == null) {
                LogUtils.e("没有选项");
            } else {
                for(int i = 0; i < ans.size(); i++) {
                    View selectView = LayoutInflater.from(this).inflate(R.layout.homework_wire_item_option, ll_options, false);
                    ll_options.addView(selectView);
                    ImageView iv_option = selectView.findViewById(R.id.iv_options);
                    mIvOptionList.add(iv_option);
                    FlexibleRichTextView frtv_option = selectView.findViewById(R.id.frtv_options);
                    frtv_option.setOnFlexibleListenerr(HomeworkWireActivity.this);
                    mFrtvOptionList.add(frtv_option);
                    List<String> myAns = StringUtil.strToList(mCurQuestion.getMyAnswer(), ",");


                    if(myAns != null && myAns.contains(OptionStr.OPS[i])) {
                        iv_option.setImageResource(R.drawable.homework_round_radio_select);
                    }
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(OptionStr.OPS[i] + ". ");
                    stringBuilder.append(FormulaUtil.reLatex(ans.get(i)));
                    mFtv_count++;
                    frtv_option.setText(stringBuilder.toString());

                    final int f_i = i;
                    selectView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(QuestionTypeUtil.isMutiChoiceQuestion(mCurQuestion.getQuestionType())) {
                                List<String> myAns2 = StringUtil.strToList(mCurQuestion.getMyAnswer(), ",");
                                if(myAns2 == null) {
                                    myAns2 = new ArrayList<>();
                                }
                                if(myAns2.contains(OptionStr.OPS[f_i])) {
                                    myAns2.remove(OptionStr.OPS[f_i]);
                                } else {
                                    myAns2.add(OptionStr.OPS[f_i]);
                                    Collections.sort(myAns2, (a, b) -> {
                                        return a.compareTo(b);
                                    });
                                }

                                if(StringUtil.isEmpty(mCurQuestion.getMyAnswer()) && myAns2.size() > 0) {
                                    if(mWireExam.getDealNum() == null) {
                                        setDealNum(1);
                                    } else {
                                        setDealNum(mWireExam.getDealNum().intValue() + 1);
                                    }
                                    if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                                        DBUtils.getInstance(HomeworkWireActivity.this).updateWireExam(mWireExam);
                                    }
                                } else if(!StringUtil.isEmpty(mCurQuestion.getMyAnswer()) && myAns2.size() == 0) {
                                    if(mWireExam.getDealNum().intValue() == 1) {
                                        setDealNum(null);
                                    } else if(mWireExam.getDealNum() != null && mWireExam.getDealNum().intValue() > 1){
                                        setDealNum(mWireExam.getDealNum().intValue() - 1);
                                    }
                                    if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                                        DBUtils.getInstance(HomeworkWireActivity.this).updateWireExam(mWireExam);
                                    }
                                }

                                mCurQuestion.setMyAnswer(StringUtil.strlistToString(myAns2, ","));
                            } else {
                                if(StringUtil.isEmpty(mCurQuestion.getMyAnswer())) {
                                    if(mWireExam.getDealNum() == null) {
                                        setDealNum(1);
                                    } else {
                                        setDealNum(mWireExam.getDealNum().intValue() + 1);
                                    }
                                    if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                                        DBUtils.getInstance(HomeworkWireActivity.this).updateWireExam(mWireExam);
                                    }
                                }
                                mCurQuestion.setMyAnswer(OptionStr.OPS[f_i]);
                            }
                            if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                                DBUtils.getInstance(HomeworkWireActivity.this).updateWireQuestion(mCurQuestion);
                            }

                            List<String> myAns3 = StringUtil.strToList(mCurQuestion.getMyAnswer(), ",");
                            for(int j = 0; j < mIvOptionList.size(); j++) {
                                if(myAns3.contains(OptionStr.OPS[j])) {
                                    mIvOptionList.get(j).setImageResource(R.drawable.homework_round_radio_select);
                                } else {
                                    mIvOptionList.get(j).setImageResource(R.drawable.homework_round_radio_unselect);
                                }
                            }

                            if(!QuestionTypeUtil.isMutiChoiceQuestion(mCurQuestion.getQuestionType())) {
                                //切换下一题
                                autoNextQuestion();
                            }
                        }
                    });
                }
            }
        }
    }

    private void autoNextQuestion() {
        mIsSwitchAndSavingImg = true;
        Observable.timer(100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer< Long >() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Long aLong) {
                        LogUtils.d("m1:onNext " + aLong + ", threadName = " + Thread.currentThread().getName());
                        mIsSwitchAndSavingImg = false;
                        autoNextQuestion_real();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void autoNextQuestion_real() {
        if(!mIsLastQuestion) {
            WireQuestion question = null;
            for(int i = mCurQuesitonPostion + 1; i < mHomeworkWireNumAdapter.getItemCount(); i++) {
                WireQuestion item = mHomeworkWireNumAdapter.getQuestion(i);
                if(QuestionTypeUtil.isObjectQuestion(item.getQuestionType())) {
                    if(StringUtil.isEmpty(item.getMyAnswer())) {
                        question = item;
                        break;
                    }
                } else if(QuestionTypeUtil.isSubjectQuestion(item.getQuestionType())) {
                    if(!item.getIsSubjectMyAns()) {
                        question = item;
                        break;
                    }
                }
            }
            if(question == null) {
                question = mHomeworkWireNumAdapter.getQuestion(mCurQuesitonPostion + 1);
            }
            mHomeworkWireNumAdapter.setmQuestionId(question.getQuestionId());
        }
    }

    private void resetFrtView() {
        if(mFrtvOptionList != null && mFrtvOptionList.size() > 0) {
            for(FlexibleRichTextView frtv : mFrtvOptionList) {
                frtv.resetTextView();
            }
        }
    }

    private void initLoadQuestionPicture() {
        mDoodle_bimap_0 = null;
        mDoodle_bimap_1 = null;
        mDoodle_bimap_2 = null;
        fl_doodle_0.removeAllViews();
        fl_doodle_1.removeAllViews();
        fl_doodle_2.removeAllViews();
        fl_doodle_0.setVisibility(View.GONE);
        fl_doodle_1.setVisibility(View.GONE);
        fl_doodle_2.setVisibility(View.GONE);
        mGraffitiView = null;
        mGraffitiTouchGestureListener = null;
        mCurQuestionPic = null;

        if(mCurQuestionPicList == null || mCurQuestionPicList.size() <= 0) {
            //客观题或者主观题没有作答才会走着一部分
            if(mIsSwitchAndSavingImg) {
                //取消这个加载框
                mIsSwitchAndSavingImg = false;
                DialogXUtil.waitDialogDismiss();
            }
        } else {
            mLoadImgIndex = 0;
            mIsInitLoadingImg = true;
            if(mIsSwitchAndSavingImg) {
                //不需要弹加载框，因为已经有加载框了,也不能取消这个加载框
                mIsSwitchAndSavingImg = false;
            } else {
                //弹加载框
                DialogXUtil.waitDialogShow("正在加载数据...");
            }
            loadQuestionPicture();
        }
    }

    private void loadQuestionPicture() {
        if(mLoadImgIndex >= mCurQuestionPicList.size()) {
            setQuestionPictureView();
            mIsInitLoadingImg = false;
            //取消加载框
            DialogXUtil.waitDialogDismiss();
            return;
        }

        String path_c = mMoudle == TsdService.MODULE_SMALLTEST_LINE
                ? FileUtils.getPicFilePath(this, "smallTestWire" + File.separator + "c", "" + mPublishId + "_" + mStudentExamId + "_" + mCurQuestion.getQuestionId() + "_" + mCurQuestionPicList.get(mLoadImgIndex).getPageIndex(), "")
                : FileUtils.getPicFilePath(this, "wire" + File.separator + "c", "" + mPublishId + "_" + mStudentExamId + "_" + mCurQuestion.getQuestionId() + "_" + mCurQuestionPicList.get(mLoadImgIndex).getPageIndex(), "");
        File f_c = new File(path_c);
        if(!f_c.exists()) {
            loadQuestionPictureFail();
            return;
        }

        Glide.with(this).asBitmap().load(path_c).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        LogUtils.e("m1:Glde图片-成功  = " + path_c + ", threadName = " + Thread.currentThread().getName());
                        if(mLoadImgIndex == 0) {
                            mDoodle_bimap_0 = resource;
                        } else if(mLoadImgIndex == 1) {
                            mDoodle_bimap_1 = resource;
                        } else if(mLoadImgIndex == 2) {
                            mDoodle_bimap_2 = resource;
                        }
                        mLoadImgIndex++;
                        loadQuestionPicture();
                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        super.onLoadFailed(errorDrawable);
                        LogUtils.e("m1:Glde图片-失败  = " + path_c + ", threadName = " + Thread.currentThread().getName());
                        //图片已经损坏要处理
                        f_c.delete();
                        loadQuestionPictureFail();
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

    private void loadQuestionPictureFail() {
        Bitmap bmp = null;
        if(mLoadImgIndex == 0) {
            bmp= BitmapFactory.decodeResource(getResources(), R.drawable.common_caogaozhi_0);
            mDoodle_bimap_0 = resizeImage(bmp);
        } else if(mLoadImgIndex == 1) {
            bmp= BitmapFactory.decodeResource(getResources(), R.drawable.common_caogaozhi_1);
            mDoodle_bimap_1 = resizeImage(bmp);
        } else if(mLoadImgIndex == 2) {
            bmp= BitmapFactory.decodeResource(getResources(), R.drawable.common_caogaozhi_2);
            mDoodle_bimap_2 = resizeImage(bmp);
        }
        mLoadImgIndex++;
        loadQuestionPicture();
    }

    private void setQuestionPictureView() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        if(mDoodle_bimap_0 != null) {
            ImageView iv = new ImageView(this);
            iv.setScaleType(ImageView.ScaleType.FIT_START);
            iv.setImageBitmap(mDoodle_bimap_0);
            fl_doodle_0.addView(iv, params);
            fl_doodle_0.setVisibility(View.VISIBLE);
        }

        if(mDoodle_bimap_1 != null) {
            ImageView iv = new ImageView(this);
            iv.setScaleType(ImageView.ScaleType.FIT_START);
            iv.setImageBitmap(mDoodle_bimap_1);
            fl_doodle_1.addView(iv, params);
            fl_doodle_1.setVisibility(View.VISIBLE);
        }

        if(mDoodle_bimap_2 != null) {
            ImageView iv = new ImageView(this);
            iv.setScaleType(ImageView.ScaleType.FIT_START);
            iv.setImageBitmap(mDoodle_bimap_2);
            fl_doodle_2.addView(iv, params);
            fl_doodle_2.setVisibility(View.VISIBLE);
        }
    }

    private void nextDots() {
        if (isNextDot()) {
            mCurDot = mOffLineDots.poll();
            analysisDots();
        }
    }

    private void setDealNum(Integer num) {
        mWireExam.setDealNum(num);
        int num2 = 0;
        if(num != null) {
            num2 = num.intValue();
        }
        EventBus.getDefault().postSticky(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_ANSWER_PROGRESS,
                mExamId + "###" + mPublishId + "###" + num2));
    }

    private void analysisDots() {
        if(mCurDot.state == TsdService.PEN_DOWN_MESSAGE) {
            if(!mCurQuestion.getIsSubjectMyAns()) {
                mCurQuestion.setIsSubjectMyAns(true);
                if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                    DBUtils.getInstance(this).updateWireQuestion(mCurQuestion);
                }
                int dealNum = mWireExam.getDealNum() == null ? 0 : mWireExam.getDealNum();
                setDealNum(++dealNum);
                if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                    DBUtils.getInstance(this).updateWireExam(mWireExam);
                }

            }
        }
        mHavePic_temp = false;
        mSwitchPic_temp = false;
        if(mCurQuestionPicList == null || mCurQuestionPicList.size() <= 0) {
            //没有写一张图片
            mHavePic_temp = false;
            mSwitchPic_temp = true;
        } else {
            for(int i = 0; i < mCurQuestionPicList.size(); i++) {
                if(mCurDot.pageAddress.equals(mCurQuestionPicList.get(i).getPageSerial())) {
                    if(mCurQuestionPic != null && mCurQuestionPic.getPageSerial().equals(mCurDot.pageAddress)) {
                        //绘制的是当前图片
                        mHavePic_temp = true;
                        mSwitchPic_temp = false;
                    } else {
                        mCurQuestionPic = mCurQuestionPicList.get(i);
                        mHavePic_temp = true;
                        mSwitchPic_temp = true;
                    }
                    break;
                }
            }
            if(!mHavePic_temp && !mSwitchPic_temp && mCurQuestionPicList.size() < (mMoudle == TsdService.MODULE_SMALLTEST_LINE ? 1 : 3)) {
                mHavePic_temp = false;
                mSwitchPic_temp = true;
            }
        }

        if(mHavePic_temp) {
            if(mSwitchPic_temp) {
                //切换到本题另外一张已有图片
                switchPicture_pre();
            } else {
                //直接绘制
                drawBitmap();
            }
        } else {
            if(mSwitchPic_temp) {
                //图片列表为null， 或者没有满3张
                //增加一张新图片

                if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
                    if(mPicId_temp == null) {
                        mPicId_temp = 1L;
                    } else {
                        mPicId_temp = mPicId_temp.longValue() + 1;
                    }
                } else {
                    mPicId_temp = null;
                }
                mCurQuestionPic = new WireQuestionPicture(mPicId_temp, null, null, null, null, mCurDot.pageAddress, null, null, null, null, mCurQuestionPicList == null ? 0 : mCurQuestionPicList.size(), null, mCurQuestion.getId());
                Bitmap bmp = null;
                if(mCurQuestionPicList == null || mCurQuestionPicList.size() == 0) {
                    bmp= BitmapFactory.decodeResource(getResources(), R.drawable.common_caogaozhi_0);
                    mDoodle_bimap_0 = resizeImage(bmp);
                } else if(mCurQuestionPicList.size() == 1) {
                    bmp= BitmapFactory.decodeResource(getResources(), R.drawable.common_caogaozhi_1);
                    mDoodle_bimap_1 = resizeImage(bmp);
                } else if(mCurQuestionPicList.size() == 2) {
                    bmp= BitmapFactory.decodeResource(getResources(), R.drawable.common_caogaozhi_2);
                    mDoodle_bimap_2 = resizeImage(bmp);
                }
                mCurQuestionPicList.add(mCurQuestionPic);
                if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                    DBUtils.getInstance(this).insertWireQuestionPicture(mCurQuestionPic);
                }
                switchPicture_pre();

            } else {
                //提示一题最多三张图片，（在按下是提示）
                if(mCurDot.state == TsdService.PEN_DOWN_MESSAGE) {
                    ToastUtil.initToast("一题最多写" + (mMoudle == TsdService.MODULE_SMALLTEST_LINE ? 1 : 3) + "张图片~");
                }
            }
        }
    }

    private void switchPicture_pre() {
        if(mGraffitiView != null) {
            saveGraffitiView(DOODLE_SAVE_TYPE_SWITCH);
        } else {
            mIsSwitchAndSavingImg = true;
            mDoodleSaveType = DOODLE_SAVE_TYPE_SWITCH;
            switchPicture();
        }
    }

    private void switchPicture() {
        mMin_h = mCurQuestionPic.getMin_h();
        mMax_h = mCurQuestionPic.getMax_h();

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        if(mDoodle_bimap_0 != null && mCurQuestionPic.getPageIndex().intValue() != 0
                && fl_doodle_0.getChildAt(0) != null
                && fl_doodle_0.getChildAt(0) instanceof GraffitiView) {
            fl_doodle_0.removeAllViews();
            ImageView iv = new ImageView(this);
            iv.setScaleType(ImageView.ScaleType.FIT_START);
            iv.setImageBitmap(mDoodle_bimap_0);
            fl_doodle_0.addView(iv, params);
            fl_doodle_0.setVisibility(View.VISIBLE);
        }

        if(mDoodle_bimap_1 != null && mCurQuestionPic.getPageIndex().intValue() != 1
                && fl_doodle_1.getChildAt(0) != null
                && fl_doodle_1.getChildAt(0) instanceof GraffitiView) {
            fl_doodle_1.removeAllViews();
            ImageView iv = new ImageView(this);
            iv.setScaleType(ImageView.ScaleType.FIT_START);
            iv.setImageBitmap(mDoodle_bimap_1);
            fl_doodle_1.addView(iv, params);
            fl_doodle_1.setVisibility(View.VISIBLE);
        }

        if(mDoodle_bimap_2 != null && mCurQuestionPic.getPageIndex().intValue() != 2
                && fl_doodle_2.getChildAt(0) != null
                && fl_doodle_2.getChildAt(0) instanceof GraffitiView) {
            fl_doodle_2.removeAllViews();
            ImageView iv = new ImageView(this);
            iv.setScaleType(ImageView.ScaleType.FIT_START);
            iv.setImageBitmap(mDoodle_bimap_2);
            fl_doodle_2.addView(iv, params);
            fl_doodle_2.setVisibility(View.VISIBLE);
        }

        Bitmap bitmap = null;
        if(mCurQuestionPic.getPageIndex().intValue() == 0) {
            fl_doodle_0.removeAllViews();
            fl_doodle_0.setVisibility(View.VISIBLE);
            bitmap = mDoodle_bimap_0;
        } else if(mCurQuestionPic.getPageIndex().intValue() == 1) {
            fl_doodle_1.removeAllViews();
            fl_doodle_1.setVisibility(View.VISIBLE);
            bitmap = mDoodle_bimap_1;
        } else if(mCurQuestionPic.getPageIndex().intValue() == 2) {
            fl_doodle_2.removeAllViews();
            fl_doodle_2.setVisibility(View.VISIBLE);
            bitmap = mDoodle_bimap_2;
        }
        initGraffitiData(bitmap);
    }

    private void initGraffitiData(Bitmap bitmap) {
        mGraffitiView = new GraffitiView(this, bitmap, null, false, false, new GraffitiView.IGraffitiViewListener(){

            @Override
            public void onSaved(List<Bitmap> bitmaps) {
                LogUtils.i("m1:涂鸦保存成功"  + ", threadName = " + Thread.currentThread().getName());


                WireQuestionPicture wireQuestionPicture = mMoudle == TsdService.MODULE_SMALLTEST_LINE ? mCurQuestionPic : DBUtils.getInstance(HomeworkWireActivity.this).getWireQuestionPictureByWireQuestionIdAndPageSerialAndPageIndex(mCurQuestion.getId(), mCurQuestionPic.getPageSerial(), mCurQuestionPic.getPageIndex());
                mCurQuestionPic.setMin_h(mMin_h);
                mCurQuestionPic.setMax_h(mMax_h);
                wireQuestionPicture.setMin_h(mMin_h);
                wireQuestionPicture.setMax_h(mMax_h);
                if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                    DBUtils.getInstance(HomeworkWireActivity.this).updateWireQuestionPicture(wireQuestionPicture);
                }
                Bitmap clip_bitmap = Bitmap.createBitmap(bitmaps.get(0), 0, mMin_h - mTran_h < 0 ? 0 : (int) (mMin_h - mTran_h), bitmaps.get(0).getWidth(), mMax_h + mTran_h > bitmaps.get(0).getHeight() ? bitmaps.get(0).getHeight() : (int) (mMax_h + mTran_h));
                bitmaps.add(clip_bitmap);


                int index = 0;
                if(fl_doodle_0.getChildAt(0) != null
                        && fl_doodle_0.getChildAt(0) instanceof GraffitiView) {
                    mDoodle_bimap_0 = bitmaps.get(0);
                    index = 0;
                } else if(fl_doodle_1.getChildAt(0) != null
                        && fl_doodle_1.getChildAt(0) instanceof GraffitiView) {
                    mDoodle_bimap_1 = bitmaps.get(0);
                    index = 1;
                } else if(fl_doodle_2.getChildAt(0) != null
                        && fl_doodle_2.getChildAt(0) instanceof GraffitiView) {
                    mDoodle_bimap_2 = bitmaps.get(0);
                    index = 2;
                }
                final int f_index = index;
                Observable.create(new ObservableOnSubscribe<Integer>() {
                    @Override
                    public void subscribe(final ObservableEmitter<Integer> emitter) throws Exception {
                        LogUtils.i("========================= subscribe currentThread name: " + Thread.currentThread().getName());
                        if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
                            FileUtils.saveBitmap(bitmaps.get(0), FileUtils.getPicFilePath(HomeworkWireActivity.this, "smallTestWire" + File.separator + "c", "" + mPublishId + "_" + mStudentExamId + "_" + mCurQuestion.getQuestionId() + "_" + mCurQuestionPicList.get(f_index).getPageIndex(), ""));
                            FileUtils.saveBitmap(bitmaps.get(1), FileUtils.getPicFilePath(HomeworkWireActivity.this, "smallTestWire" + File.separator + "t", "" + mPublishId + "_" + mStudentExamId + "_" + mCurQuestion.getQuestionId() + "_" + mCurQuestionPicList.get(f_index).getPageIndex(), ""));
                        } else {
                            FileUtils.saveBitmap(bitmaps.get(0), FileUtils.getPicFilePath(HomeworkWireActivity.this, "wire" + File.separator + "c", "" + mPublishId + "_" + mStudentExamId + "_" + mCurQuestion.getQuestionId() + "_" + mCurQuestionPicList.get(f_index).getPageIndex(), ""));
                            FileUtils.saveBitmap(bitmaps.get(1), FileUtils.getPicFilePath(HomeworkWireActivity.this, "wire" + File.separator + "t", "" + mPublishId + "_" + mStudentExamId + "_" + mCurQuestion.getQuestionId() + "_" + mCurQuestionPicList.get(f_index).getPageIndex(), ""));
                        }

                        emitter.onNext(1);
                        emitter.onComplete();

                    }
                }).subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<Integer>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                                //创建只运行1次，执行顺序1 -- main
                                LogUtils.i("========================= onSubscribe currentThread name: " + Thread.currentThread().getName());

                            }

                            @Override
                            public void onNext(Integer o) {
                                //运行多次 执行顺序3 -- thread
                                LogUtils.i("========================= onNext currentThread name: " + Thread.currentThread().getName());
                                if(mDoodleSaveType == DOODLE_SAVE_TYPE_SWITCH) {
                                    switchPicture();
                                } else if(mDoodleSaveType == DOODLE_SAVE_TYPE_SUBMIT) {
                                    mIsSwitchAndSavingImg = false;
                                    //保持加载框显示
                                    clickSubmit();
                                } else if(mDoodleSaveType == DOODLE_SAVE_TYPE_EXIT) {
                                    mIsSwitchAndSavingImg = false;
                                    //取消加载框
                                    DialogXUtil.waitDialogDismiss();
                                    finish();
                                } else if(mDoodleSaveType == DOODLE_SAVE_NEXT_QUESTION) {
                                    clickNextQuestion();
                                } else if(mDoodleSaveType == DOODLE_SAVE_ITEM_QUESTION) {
                                    clickItemQuestion();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                //运行1次  -- thread
                                LogUtils.i("========================= onError currentThread name: " + Thread.currentThread().getName() + "--" + e.getMessage());

                            }

                            @Override
                            public void onComplete() {
                                //运行1次  -- thread
                                LogUtils.i("========================= onComplete currentThread name: " + Thread.currentThread().getName());

                            }
                        });
            }
        });
        mGraffitiTouchGestureListener = new GraffitiOnTouchGestureListener(mGraffitiView, new GraffitiOnTouchGestureListener.IGraffitiOnTouchGestureListener() {
            @Override
            public void onTest() {

            }
            @Override
            public void onCallScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                LogUtils.i("m1:滚动手指：distanceX: " + distanceX + ", distanceY:" + distanceY);
            }
        });

        IGraffitiTouchDetector detector = new GraffitiTouchDetector(this, mGraffitiTouchGestureListener);
        mGraffitiView.setDefaultTouchDetector(detector);

        mGraffitiTouchGestureListener.setSupportScale(false); //禁止放大缩小
        setSupportDoodle(false);
        setSupportTrans(false);
        mGraffitiTouchGestureListener.setTouchType(GraffitiOnTouchGestureListener.TOUCH_TYPE_ALL);

        //graffitiView.setStartXy(true);
        mGraffitiView.setColor(Color.BLACK);
        mGraffitiView.setIsDrawableOutside(false);
        mGraffitiView.setSize(4);

        if(mCurQuestionPic.getPageIndex() == 0) {
            fl_doodle_0.addView(mGraffitiView);
        } else if(mCurQuestionPic.getPageIndex() == 1) {
            fl_doodle_1.addView(mGraffitiView);
        } else if(mCurQuestionPic.getPageIndex() == 2) {
            fl_doodle_2.addView(mGraffitiView);
        }
        delayToDot(300);
    }

    private void setSupportDoodle(boolean isSupport) {
        if (mGraffitiTouchGestureListener != null) {
            mGraffitiTouchGestureListener.setSupportGraffiti(isSupport);
        }
    }

    private void setSupportTrans(boolean isSupport) {
        if (mGraffitiTouchGestureListener != null) {
            mGraffitiTouchGestureListener.setSupportTrans(isSupport);
        }
    }

    private void saveGraffitiView(int type) {
        mIsSwitchAndSavingImg = true;
        //弹加载框
        DialogXUtil.waitDialogShow("正在保存图片...");
        mDoodleSaveType = type;
        mGraffitiView.save();
    }

    private void delayToDot(int time) {
        Observable.timer(time, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer< Long >() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Long aLong) {
                        LogUtils.d("m1:onNext " + aLong + ", threadName = " + Thread.currentThread().getName());
                        if(mDoodleSaveType == DOODLE_SAVE_TYPE_SWITCH) {
                            mIsSwitchAndSavingImg = false;
                            //取消加载框
                            DialogXUtil.waitDialogDismiss();
                        }
                        drawBitmap();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void drawBitmap() {
        mTemp_x = TsdPenUtil.getRealX(mCurDot.coordX, (int)mO_w) * mScale;
        mTemp_y = TsdPenUtil.getRealY(mCurDot.coordY, (int)mO_h) * mScale;
        if(mMin_h == null) {
            mMin_h = mTemp_y;
        }
        if(mMax_h == null) {
            mMax_h = mTemp_y;
        }
        if(mTemp_y > mMax_h.floatValue()) {
            mMax_h = mTemp_y;
        }

        if(mTemp_y < mMin_h.floatValue()) {
            mMin_h = mTemp_y;
        }

        if (mCurDot.state == TsdService.PEN_DOWN_MESSAGE) {
            mGraffitiTouchGestureListener.r_onDown(mTemp_x, mTemp_y);
            mGraffitiTouchGestureListener.r_onScrollBegin(mTemp_x, mTemp_y);
        } else if (mCurDot.state == TsdService.PEN_COODINAT_MESSAGE) {
            mGraffitiTouchGestureListener.r_onScroll(mTemp_x, mTemp_y);
        } else if (mCurDot.state == TsdService.PEN_UP_MESSAGE) {
            mGraffitiTouchGestureListener.r_onScrollEnd(mTemp_x, mTemp_y);
        }
        nextDots();
    }

    public Bitmap resizeImage(Bitmap bitmap) {

        int bmpWidth = bitmap.getWidth();
        int bmpHeight = bitmap.getHeight();

        Matrix matrix = new Matrix();
        matrix.postScale(mScale, mScale);

        return Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
    }

    private void showNoPenConnectDialog(boolean isAgain) {
        String mac = SPUtils.getInstance().getString(Constants.USER_PEN_MAC);
        if(StringUtil.isEmpty(mac) || isAgain) {
            DialogXUtil.customDialogShow(isAgain ? "自动重连失败！" : "智能笔连接未连接！\r\n请连接智能笔后再作答", "", "手动连接", true, new DialogXUtil.OnDialogXListen() {
                @Override
                public void onListenDialogOk() {

                }

                @Override
                public void onListenDialogCancel() {
                    //手动连接
                    ARouter.getInstance().build(ConstantArouter.PATH_PEN_PENMAINACTIVITY).navigation();
                }

                @Override
                public void onListenDialogClose() {

                }
            });
        } else {
            DialogXUtil.customDialogShow("智能笔连接未连接！\r\n请连接智能笔后再作答", "刷新自动重连", "手动连接", new DialogXUtil.OnDialogXListen() {
                @Override
                public void onListenDialogOk() {
                    //自动连接
                    mIsPenAutoConnect = true;
                    DialogXUtil.waitDialogShow("正在自动连接智能笔...");
                    mTsdServiceBinder.on_startScan();
                }

                @Override
                public void onListenDialogCancel() {
                    //手动连接
                    ARouter.getInstance().build(ConstantArouter.PATH_PEN_PENMAINACTIVITY).navigation();
                }

                @Override
                public void onListenDialogClose() {

                }
            });
        }
    }

    private void delayToOutLogin() {
        Observable.timer(2000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer< Long >() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Long aLong) {
                        LogUtils.d("m1:onNext " + aLong + ", threadName = " + Thread.currentThread().getName());
                        DialogUtil.getInstance().reLoginDialog(HomeworkWireActivity.this, "账号已在其他设备登录，\r\n请重新登录");
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void exitActivity() {
        DialogXUtil.customDialogShow("退出会缓存作答数据，\r\n确定要退出作答吗？", "确定", "取消", new DialogXUtil.OnDialogXListen() {
            @Override
            public void onListenDialogOk() {
                if(mGraffitiView != null) {
                    saveGraffitiView(DOODLE_SAVE_TYPE_EXIT);
                }else {
                    finish();
                }
            }

            @Override
            public void onListenDialogCancel() {

            }

            @Override
            public void onListenDialogClose() {

            }
        });
    }

    private int getNoAnswerNum() {
        int num = 0;
        List<WireQuestion> questionList = null;
        if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
            questionList = mWireExam.getQuestionList2();
        } else {
            questionList = mWireExam.getQuestionList();
        }
        for(WireQuestion item : questionList) {
            if(QuestionTypeUtil.isSubjectQuestion(item.getQuestionType())) {
                if(!item.getIsSubjectMyAns()) {
                    num++;
                }
            } else {
                if(StringUtil.isEmpty(item.getMyAnswer())) {
                    num++;
                }
            }
        }
        /*EventBus.getDefault().postSticky(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_ANSWER_PROGRESS,
                mExamId + "###" + mPublishId + "###" + num));*/
        return num;
    }

    private void clickSubmit_pre() {
        //弹出加载框
        DialogXUtil.waitDialogShow("正在上传作答...");
        if(mGraffitiView != null) {
            mIsSubmiting = true;
            saveGraffitiView(DOODLE_SAVE_TYPE_SUBMIT);
        } else {
            clickSubmit();
        }
    }

    private void clickSubmit() {
        mOssCount = 0;
        mOssParamsList.clear();
        WireExam exam = null;
        if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
            exam = mWireExam;
        } else {
            exam = DBUtils.getInstance(this).getWireExamById(mWireExam.getId());
        }

        if(exam == null) {
            mIsSubmiting = false;
            DialogXUtil.waitDialogDismiss();

            ToastUtil.initToast("数据库出错了 exam == null");
            return;
        }
        List<WireQuestion> questionList = null;
        if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
            questionList = mWireExam.getQuestionList2();
        } else {
            questionList = mWireExam.getQuestionList();
        }
        for(WireQuestion item : questionList) {
            List<WireQuestionPicture> picList = null;
            if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
                picList = item.getWireQuestionPictureList2();
            } else {
                picList = item.getWireQuestionPictureList();
            }
            for(WireQuestionPicture item2 : picList) {
                String filePath = mMoudle == TsdService.MODULE_SMALLTEST_LINE
                        ? FileUtils.getPicFilePath(HomeworkWireActivity.this, "smallTestWire" + File.separator + "t", "" + mPublishId + "_" + mStudentExamId + "_" + item.getQuestionId() + "_" + item2.getPageIndex(), "")
                        : FileUtils.getPicFilePath(HomeworkWireActivity.this, "wire" + File.separator + "t", "" + mPublishId + "_" + mStudentExamId + "_" + item.getQuestionId() + "_" + item2.getPageIndex(), "");
                File file = new File(filePath);
                if(file.exists()) {
                    mOssCount++;
                    final String uploadFileName = item2.getPageIndex() + TsdService.str_teacher_index_split + "" + mPublishId + "_" + mStudentExamId + "_" + item.getQuestionId() + "_" + item2.getPageIndex() + "_"  + System.currentTimeMillis() + ".png";
                    OssParams ossParams = new OssParams(item2.getId(), null, uploadFileName, filePath);
                    mOssParamsList.add(ossParams);
                }
            }
        }

        osssUploadByOssCount();
        isOssSuccess();
    }

    private void osssUploadByOssCount() {
        if(mOssCount > 0) {
            OssParams params = mOssParamsList.get(mOssParamsList.size() - mOssCount);
            UploadOss.getInstance().upload2OSS(params.getUploadFileName(), params.getFilePath(), ossUploadListener, params);
        }
    }

    private void isOssSuccess() {
        LogUtils.i("m1: isOssSuccess: mOssCount=" + mOssCount + ", mIssubmitSuccess=" + mIsSubmitSuccess);
        if(mOssCount == 0 && mIsSubmitSuccess) {
            if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
                submitData_pre_smallTest();
            } else {
                submitData_pre();
            }
        } else {
            isSubmitSuccess();
        }
    }

    private void isSubmitSuccess() {
        if(mOssCount == 0 && mIsSubmitSuccess) {
            //弹提示框，提交成功
            if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
                ToastUtil.initToast("提交作业成功");
            }
        } else if(!mIsSubmitSuccess){
            mIsSubmitSuccess = true;
            //弹提示框，提交失败
            ToastUtil.initToast("提交作业失败");
        }
    }

    UploadOss.OnUploadListener ossUploadListener = new UploadOss.OnUploadListener() {
        @Override
        public String uploadSuccess(String uploadFile, String localFile, OssParams ossParams) {
            LogUtils.i("m1:-----ossUploadListener uploadSuccess threadName: "+Thread.currentThread().getName());
            saveOssPathToDb(ossParams, uploadFile);
            mOssCount--;
            isOssSuccess();
            osssUploadByOssCount();
            return null;
        }

        @Override
        public String uploadFail(String uploadFile, String localFile, OssParams ossParams) {
            LogUtils.i("m1:-----ossUploadListener uploadSuccess threadName: "+Thread.currentThread().getName());
            mOssCount--;
            mIsSubmitSuccess = false;
            isOssSuccess();
            if("-1".equals(uploadFile)) {
                delayToOutLogin();
            }
            return null;
        }
    };

    private void saveOssPathToDb(OssParams ossParams, String uploadFile) {
        long questionPicId = ossParams.getId();
        if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
            for(WireQuestion item : mWireExam.getQuestionList2()) {
                for(WireQuestionPicture item2: item.getWireQuestionPictureList2()) {
                    if(item2.getId().longValue() == questionPicId) {
                        item2.setOssPath(uploadFile);
                    }
                }
            }
        } else {
            WireQuestionPicture picture = DBUtils.getInstance(this).getWireQuestionPictureById(questionPicId);
            picture.setOssPath(uploadFile);
            DBUtils.getInstance(this).updateWireQuestionPicture(picture);
        }

    }

    private void submitData_pre() {
        WireExam wireExam =  DBUtils.getInstance(this).getWireExamById(mWireExam.getId());
        CommitAnswerReq req = new CommitAnswerReq();
        req.setStudentExamId(mStudentExamId);
        req.setStudentId(Integer.parseInt(mStudentId));
        req.setBeginTime(wireExam.getBeginTime());
        req.setFinishTime(ComUtil.getStringDate());

        List<CommitAnswerReq_vo> vList = new ArrayList<>();
        for(WireQuestion item : wireExam.getQuestionList()) {
            CommitAnswerReq_vo vo = new CommitAnswerReq_vo();
            vo.setQuestionId(item.getQuestionId());
            vo.setQuestionType(item.getQuestionType());
            if(QuestionTypeUtil.isObjectQuestion(item.getQuestionType())) {
                vo.setAnswerType(1);
                vo.setAnswerContent(item.getMyAnswer());
            } else {
                vo.setAnswerType(2);
                String str_path = null;
                if(item.getWireQuestionPictureList() != null) {
                    for(WireQuestionPicture item2 : item.getWireQuestionPictureList()) {
                        if(str_path == null && item2.getOssPath() != null) {
                            str_path = item2.getOssPath();
                        } else if(item2.getOssPath() != null) {
                            str_path = str_path + "," + item2.getOssPath();
                        }
                    }
                }

                vo.setAnswerContent(str_path);
            }
            vList.add(vo);
        }
        req.setQuestionList(vList);
        String json = JsonUtils.toJson(req);
        LogUtils.i("提交数据：" + json);
        getPresenter().getCommitAnswer(json, false, false);
    }

    private void submitData_pre_smallTest() {
        if(mTsdServiceBinder == null) {
            LogUtils.e("mTsdServiceBinder == null");
            return;
        }
        if(mTsdServiceBinder.on_getmStudentJoinRoom_command() == null) {
            LogUtils.e("mTsdServiceBinder.on_getmStudentJoinRoom_command() == null");
            return;
        }
        if(mTsdServiceBinder.on_getmSmallTest_command() == null) {
            LogUtils.e("mTsdServiceBinder.on_getmSmallTest_command() == null");
            return;
        }
        SmallTestCommitReq req = new SmallTestCommitReq();
        req.setInstructions("studentCommitExam");
        req.setId(mStudentId);
        req.setRoomId(mRoomId);
        req.setBeginTime(mWireExam.getBeginTime());
        req.setFinishTime(ComUtil.getStringDate());
        req.setExamId(mExamId);
        req.setPublishId(mPublishId);
        //req.setIsLine(mTsdServiceBinder.on_getmSmallTest_command().getIsLine());
        req.setIsLine(1);
        List<SmallTestCommitReq_questionList> qList = new ArrayList<>();
        for(WireQuestion item : mWireExam.getQuestionList2()) {
            SmallTestCommitReq_questionList vo = new SmallTestCommitReq_questionList();
            if(QuestionTypeUtil.isObjectQuestion(item.getQuestionType())) {
                vo.setAnswerType(1);
                vo.setAnswerContent(item.getMyAnswer());
            } else {
                vo.setAnswerType(2);
                if(item.getWireQuestionPictureList2() != null && item.getWireQuestionPictureList2().size() > 0) {
                    vo.setAnswerContent(item.getWireQuestionPictureList2().get(0).getOssPath());
                }
            }
            vo.setQuestionId(item.getQuestionId());
            vo.setQuestionType(item.getQuestionType());
            qList.add(vo);
        }
        req.setQuestionList(qList);
        //String json = JsonUtils.toJson(req);

        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_WEBSOCKE_SMALLTEST_COMMIT, JsonUtils.toJson(req)));
        mTsdServiceBinder.on_setmModule(TsdService.MODULE_ROOM);
        deleteDataAndFile();

    }

    private void deleteDataAndFile() {
        WireExam wireExam =  mMoudle == TsdService.MODULE_SMALLTEST_LINE ? mWireExam : DBUtils.getInstance(this).getWireExamById(mWireExam.getId());
        if(wireExam != null) {
            List<WireQuestion> questionList = null;
            if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
                questionList = mWireExam.getQuestionList2();
            } else {
                questionList = mWireExam.getQuestionList();
            }
            for(WireQuestion item : questionList) {
                List<WireQuestionPicture> picList = null;
                if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
                    picList = item.getWireQuestionPictureList2();
                } else {
                    picList = item.getWireQuestionPictureList();
                }
                if(picList != null) {
                    for(WireQuestionPicture item2 : picList) {
                        String path_c = mMoudle == TsdService.MODULE_SMALLTEST_LINE
                                ? FileUtils.getPicFilePath(this, "smallTestWire" + File.separator + "c", "" + mPublishId + "_" + mStudentExamId + "_" + item.getQuestionId() + "_" + item2.getPageIndex(), "")
                                : FileUtils.getPicFilePath(this, "wire" + File.separator + "c", "" + mPublishId + "_" + mStudentExamId + "_" + item.getQuestionId() + "_" + item2.getPageIndex(), "");
                        String path_t = mMoudle == TsdService.MODULE_SMALLTEST_LINE
                                ? FileUtils.getPicFilePath(this, "smallTestWire" + File.separator + "t", "" + mPublishId + "_" + mStudentExamId + "_" + item.getQuestionId() + "_" + item2.getPageIndex(), "")
                                : FileUtils.getPicFilePath(this, "wire" + File.separator + "t", "" + mPublishId + "_" + mStudentExamId + "_" + item.getQuestionId() + "_" + item2.getPageIndex(), "");
                        File f_c = new File(path_c);
                        File f_t = new File(path_t);
                        if(f_c.exists()) {
                            f_c.delete();
                        }
                        if(f_t.exists()) {
                            f_t.delete();
                        }
                        if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                            DBUtils.getInstance(this).deleteWireQuestionPictureById(item2.getId());
                        }
                    }
                }
                if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                    DBUtils.getInstance(this).deleteWireQuestionById(item.getId());
                }
            }
            if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                DBUtils.getInstance(this).deleteWireExamById(wireExam.getId());
            }
        }

        //ToastUtil.initToast("提交作业成功");
        //mIsSubmiting = false;
        //取消加载框
        DialogXUtil.waitDialogDismiss();
        isSubmitSuccess();
        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_ANSWER_SUBMIT_SUCCESS, null));

        if(mSmallTest_TeacherSubmit) {
            mIsSubmiting = false;
            finish();
            return;
        }
        DialogXUtil.customDialogShow(mSmallTest_TeacherSubmit ? "老师主动结束作答，\r\n自动提交成功！" : "恭喜，提交成功！", "",mMoudle == TsdService.MODULE_SMALLTEST_LINE ? "好的" : "查看作答详情", true, R.drawable.common_dialog_icon_dui, new DialogXUtil.OnDialogXListen() {
            @Override
            public void onListenDialogOk() {

            }

            @Override
            public void onListenDialogCancel() {
                mIsSubmiting = false;
                if(mMoudle != TsdService.MODULE_SMALLTEST_LINE) {
                    if(mIsTupu) {
                        ARouter.getInstance().build(ConstantArouter.PATH_HOMEWORK_DETAILACTIVITY)
                                .withString("examName", mExamName)
                                .withInt("examId", mExamId)
                                .withInt("publishId", mPublishId)
                                .withInt("studentExamId", mStudentExamId)
                                .navigation();
                    } else {
                        ARouter.getInstance().build(ConstantArouter.PATH_HOMEWORK_DETAILACTIVITY)
                                .withString("examName", mExamName)
                                .withInt("examId", mExamId)
                                .withInt("publishId", mPublishId)
                                .withInt("studentExamId", mStudentExamId)
                                .navigation();

                    }
                }
                finish();
            }

            @Override
            public void onListenDialogClose() {

            }
        });
    }


    private void initSmallTestData(GetAssistantQuestionList resp_data) {
        List<WireQuestion> wireQuestionList = new ArrayList<>();
        for(GetAssistantQuestionList2 item : resp_data.getQuestionList()) {
            String options = null;
            if(item.getOptions() != null && item.getOptions().size() > 0) {
                options = StringUtil.strlistToString(item.getOptions(), "###");
            }
            String answers = null;
            if(item.getAnswers() != null && item.getAnswers().size() > 0) {
                answers = StringUtil.strlistToString(item.getAnswers(), "###");
            }

            WireQuestion wireQuestion = new WireQuestion(null, item.getQuestionId(), null, item.getQuestionNo(),
                    item.getQuestionScore(), item.getQuestionContent(), item.getQuestion(), options, item.getExplain(),
                    answers, item.getQuestionType(), item.getIsSingle(), null, null, null, null, item.getScreenIsView(),
                    item.getScreenBegin(), item.getScreenEnd(), item.getQuestionScreen(), item.getScreenType(), item.getScreenId(),
                    item.getListeningUrl(), item.getDuration(), item.getChapterId(), null, null, item.getQuestionDetailId(),
                    null, null, null, null, null, false, null);
            wireQuestion.setWireQuestionPictureList(new ArrayList<>());
            wireQuestionList.add(wireQuestion);
        }

        mWireExam = new WireExam(null, mPublishId, mStudentExamId, mExamName, mExamId, null, null,
                ComUtil.getStringDate(), null, resp_data.getQuestionList().size(), null);
        mWireExam.setQuestionList(wireQuestionList);

        initQuestionNumShow();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void busGetMessage(EventBusMessage messageEvent) {
        LogUtils.i("m1: bus-->" + messageEvent.toString());
        int action = messageEvent.getAction();
        String msg = messageEvent.getMsg();
        if(action == EventBusMessage.EVENT_BUS_ACTION_PEN_CONNECT_IS){
            if(!mIsPenAutoConnect) {
                if("已连接".equals(msg)) {

                } else if("未连接".equals(msg)) {
                    if(mMoudle == TsdService.MODULE_SMALLTEST_LINE) {
                        if(QuestionTypeUtil.isSubjectQuestion(mCurQuestion.getQuestionType())) {
                            showNoPenConnectDialog(false);
                        }
                    } else {
                        if(QuestionTypeUtil.isSubjectQuestion(mCurQuestion.getQuestionType())) {
                            showNoPenConnectDialog(false);
                        }
                    }
                }
            }
        }
    }
}
